package bb.lanxing.activity.login

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.os.CountDownTimer
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.text.method.LinkMovementMethod
import android.view.View
import bb.lanxing.App
import bb.lanxing.R
import bb.lanxing.activity.agreement.AgreementActivity
import bb.lanxing.activity.interfaces.IGetAuthCodeView
import bb.lanxing.activity.interfaces.ILoginPresenter
import bb.lanxing.activity.interfaces.ILoginView
import bb.lanxing.common.config.Constants.INTERVAL_1_MIN
import bb.lanxing.common.config.Constants.INTERVAL_1_SEC
import bb.lanxing.databinding.ActivityLoginVerificationBinding
import bb.lanxing.model.database.User
import bb.lanxing.mvp.presetner.GetAuthCodePresenterImpl
import bb.lanxing.mvp.presetner.LoginPresenterImpl
import bb.lanxing.mvp.presetner.i.IGetAuthCodePresenter
import bb.lanxing.util.InputHelper
import bb.lanxing.util.Validator
import org.json.JSONObject

class VerificationLoginActivity : AgreementActivity(), ILoginView, IGetAuthCodeView {
    private lateinit var authCodePresenter: IGetAuthCodePresenter
    private var isCountDown = false
    private lateinit var loginBinding: ActivityLoginVerificationBinding
    private lateinit var loginPresenter: ILoginPresenter
    private var timer: CountDownTimer? = null
    private var captcha = ""
    override fun onLoginByThirdPartyResult(user: User) {}
    override fun onCreate(bundle: Bundle?) {
        super.onCreate(bundle)
        loginBinding = ActivityLoginVerificationBinding.inflate(layoutInflater)
        setContentView(loginBinding.root)
        initView()
        initClick()
    }

    fun initView() {
        setTitle(R.string.mine_login_label_message_login)
        setupActionBar(true)
        val name = intent.getStringExtra("name")
        if (!TextUtils.isEmpty(name)) {
            loginBinding.phoneView.text = name
        }
        loginBinding.getAuthCodeBtn.isEnabled = false
        loginBinding.loginBtn.isEnabled = false
        loginPresenter = LoginPresenterImpl(this)
        authCodePresenter = GetAuthCodePresenterImpl(this)
        loginBinding.cbLoginUserAgreement.setOnCheckedChangeListener { _, _ -> setLoginBtnStatus() }
        loginBinding.tvLoginUserAgreement.text = getSpannableStringBuilder(this@VerificationLoginActivity)
        loginBinding.tvLoginUserAgreement.movementMethod = LinkMovementMethod.getInstance()
        loginBinding.phoneView.editText.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(editable: Editable) {}
            override fun beforeTextChanged(charSequence: CharSequence, i: Int, i2: Int, i3: Int) {}
            override fun onTextChanged(charSequence: CharSequence, i: Int, i2: Int, i3: Int) {
                setLoginBtnStatus()
            }
        })
        loginBinding.authcodeView.editText.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(editable: Editable) {}
            override fun beforeTextChanged(charSequence: CharSequence, i: Int, i2: Int, i3: Int) {}
            override fun onTextChanged(charSequence: CharSequence, i: Int, i2: Int, i3: Int) {
                setLoginBtnStatus()
            }
        })
    }

    fun setLoginBtnStatus() {
        val length = loginBinding.phoneView.text.length
        val ret =
            length > 0 && loginBinding.authcodeView.text.isNotEmpty() && loginBinding.cbLoginUserAgreement.isChecked
        loginBinding.loginBtn.isEnabled = ret
        loginBinding.getAuthCodeBtn.isEnabled = length > 0
    }

    private fun initClick() {}
    private fun startCountDown() {
        isCountDown = true
        timer = object : CountDownTimer(INTERVAL_1_MIN, INTERVAL_1_SEC) {
            override fun onTick(j: Long) {
                loginBinding.getAuthCodeBtn.text = this@VerificationLoginActivity.getString(
                    R.string.mine_profile_get_auth_code_time, (j / 1000).toString()
                )
            }

            override fun onFinish() {
//                loginBinding.authcodeView.text = captcha
                isCountDown = false
                loginBinding.getAuthCodeBtn.setText(R.string.mine_login_get_message_code)
                loginBinding.getAuthCodeBtn.isEnabled = true
            }
        }.start()
    }

    override fun onGetAuthCodeResult(z: Boolean, i: Int) {
        if (i == 1) {
            if (z) {
                return
            }
            loginBinding.voiceView.isEnabled = true
            loginBinding.voiceView.setTextColor(Color.parseColor("#ff007ac2"))
        } else if (z) {
            startCountDown()
        } else {
            if (!isCountDown) {
                loginBinding.getAuthCodeBtn.isEnabled = true
            }
        }
    }

    override fun onGetAuthCodeResult(jsonObject: JSONObject) {
        captcha = jsonObject.optString("captcha")
    }

    override fun onDestroy() {
        loginPresenter.destroy()
        val countDownTimer = timer
        countDownTimer?.cancel()
        super.onDestroy()
    }

    override fun onLoginResult(user: User) {
        runOnUiThread {
            loginBinding.loginBtn.isEnabled = true
            AccountLoginActivity.loginSuccess(user)
            setResult(-1)
            finish()
        }
    }

    fun loginBtnClick(view: View) {
        val text = loginBinding.phoneView.text
        val str = loginBinding.authcodeView.text
        loginBinding.loginBtn.isEnabled = false
        loginPresenter.loginSms(text, str)
        InputHelper.hideSoftInput(loginBinding.phoneView)
    }

    fun getVerificationCodeClick(view: View) {
        val text = loginBinding.phoneView.text
        if (Validator.isPhoneNumber(text)) {
            loginBinding.getAuthCodeBtn.isEnabled = false
            loginBinding.authcodeView.isFocusable = true
            startCountDown()
            authCodePresenter.getAuthCode(text, 10, 0)
            return
        }
        App.getContext().showMessage(R.string.mine_profile_phone_not_valid)
    }

    fun accountNumLoginClick(view: View) {
        startActivity(Intent(this, AccountLoginActivity::class.java))
        finish()
    }

    fun getVoiceAuthCodeClick(view: View) {
        if (loginBinding.voiceView.isEnabled) {
            val text = loginBinding.phoneView.text
            if (Validator.isPhoneNumber(text)) {
                loginBinding.voiceView.isEnabled = false
                loginBinding.voiceView.setTextColor(Color.parseColor("#666666"))
                authCodePresenter.getAuthCode(text, 10, 1)
                return
            }
            App.getContext().showMessage(R.string.mine_profile_phone_not_valid)
        }
    }
}